package com.example.thymeleaf.controller;

import com.example.thymeleaf.entity.User;
import com.example.thymeleaf.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/users")
public class UserController {
    private final UserService service;
    public UserController(UserService service){
        this.service=service;
    }

    @RequestMapping("/list")
    public String list(Model model){
        model.addAttribute("users",service.findAll());
        return "users/list";
    }

    @RequestMapping("/find/{id}")
    public String find(@PathVariable Integer id,Model model){
        model.addAttribute("user",service.findById(id));
        return "users/find";
    }

    @RequestMapping(value = "/insert",method = RequestMethod.POST)
    public String insert(@ModelAttribute User user, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return "redirect:/users/list";
        }
        service.save(user);
        return "redirect:/users/list";
    }


    @RequestMapping("/insert")
    public String insert(Model model){
        model.addAttribute("user",new User());
        return "users/insert";
    }

    @RequestMapping(value = "delete/{id}",method = RequestMethod.GET)
    public String delete(@PathVariable int id){
        service.delete(id);
        return "redirect:/users/list";
    }

}
